﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Quartz;
using Quartz.Logging;
using SandAbp.ScheduleTask.ScheduleMaster.Manager;
using SandAbp.ScheduleTask.Schedules;
using SandAbp.ScheduleTask.SchedulesSchedules;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Settings;

namespace SandAbp.ScheduleTask.ScheduleMaster.Job
{
    [DisallowConcurrentExecution]
    public class HttpJob
    {
        private IHttpClientFactory _httpClientFactory { get; set; }
        private IScheduleEntityRepository _scheduleEntityRepository { get; set; }
        private IScheduleLogEntityRepository _scheduleLogEntityRepository { get; set; }
        private IQuartzManager _quartzManager { get; set; }
        private ISettingProvider _settingProvider { get; set; }

        private ILogger<HttpJob> _logger { get; set; }
        public HttpJob(IHttpClientFactory httpClientFactory,
            IScheduleEntityRepository scheduleEntityRepository,
            IQuartzManager quartzManager,
            IScheduleLogEntityRepository scheduleLogEntityRepository,
            ISettingProvider settingProvider,
            ILogger<HttpJob> logger)
        {
            _httpClientFactory = httpClientFactory;
            _scheduleEntityRepository = scheduleEntityRepository;
            _quartzManager = quartzManager;
            _scheduleLogEntityRepository = scheduleLogEntityRepository;
            _settingProvider = settingProvider;

            _logger = logger;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            await Run(context);
        }

        public async Task Run(IJobExecutionContext context)
        {
            Stopwatch stopwatch = new Stopwatch();
            IJobDetail job = context.JobDetail;
            var instance = job.JobDataMap["JobParam"] as ScheduleManagerDto;
            var httpClient = _httpClientFactory.CreateClient();
            //自定头部信息  如果  要token 之类的
            string headers = instance.Headers;
            var obj = JsonConvert.DeserializeObject(headers);
            if (obj != null)
            {
                foreach (var x in obj as JObject)
                {
                    httpClient.DefaultRequestHeaders.Add(x.Key, x.Value.ToString());
                }
            }
        }
    }
}
